import { useLoginStore } from "@/stores/login";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/home",
    },
    {
      path: "/home",
      name: "home",
      component: () => import("../views/home/index.vue"),
    },
    {
      path: "/good",
      name: "good",
      component: () => import("../views/good/index.vue"),
    },
    {
      path: "/free",
      name: "free",
      component: () => import("../views/free/index.vue"),
    },
    {
      path: "/order",
      name: "order",
      redirect: "/cart",
      component: () => import("../views/order/index.vue"),
      children: [
        {
          path: "/cart",
          name: "cart",
          component: () => import("../views/order/components/cart.vue"),
        },
      ],
    },
    {
      path: "/user",
      name: "user",
      component: () => import("../views/user/index.vue"),
    },
    {
      path: "/details",
      name: "details",
      component: () => import("../components/Details.vue"),
    },
    {
      path: "/:catchAll(.*)",
      name: "404",
      component: () => import("../components/error.vue"),
    },
  ],
});
//路由守卫
//判断是否登录token，未登录，不在登录页，去登录页
//判断是否，过期？
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  // console.log(to.name);
  console.log(to.fullPath);
  if (token && to.name == "login") {
    next(from.fullPath);
  } else if (!token && to.name != "login") {
    console.log("/login");
    // ElMessage.warning("您还未登录,请先登录");
    const userStore = useUserStore();
    const loginStore = useLoginStore();
    loginStore.isShowLoginModel = true;
    userStore.resetUser();
    next();
    // next();
  } else if (to.name == "order" || to.name == "free") {
    // 如果用户未能验证身份，则 `next` 会被调用两次
    //初始化
    // console.log(222);
    if (!token) {
      ElMessage.warning("请先登录");
      next(from.fullPath);
    } else {
      next();
    }
  } else {
    next();
  }
});
export default router;
